package com.shuo.dsa.leetcode;

/**
 * Created by shuoGG on 2018/10/10 0010
 */
public class StockProfit {
    public static void main(String[] args) {
        System.out.println(twiceSell());
    }

    private static int multiSell() {
        int[] prices = new int[]{1, 2, 3, 4, 5};
        int sum = 0;
        for (int i = 0; i < prices.length - 1; i++) {
            int p = prices[i + 1] - prices[i];
            if (p > 0)
                sum += p;
        }
        return sum;
    }

    private static int singleSell() {
        int[] prices = new int[]{7, 2, 9, 4, 5};
        int min = prices[0];
        int maxProfit = prices[1] - prices[0];
        for (int i = 1; i < prices.length; i++) {
            int profit = prices[i] - min;
            if (profit > maxProfit)
                maxProfit = profit;
            if (prices[i] < min)
                min = prices[i];
        }
        return maxProfit;
    }

    /**
     * 动态规划
     *
     * @return
     */
    private static int twiceSell() {
        int[] prices = new int[]{7, 2, 9, 4, 5};
        int buy1 = Integer.MIN_VALUE;
        int buy2 = Integer.MIN_VALUE;
        int sell1 = 0;
        int sell2 = 0;
        for (int price : prices) {
            sell2 = Math.max(sell2, buy2 + price);
            buy2 = Math.max(buy2, sell1 - price);
            sell1 = Math.max(sell1, buy1 + price);
            buy1 = Math.max(buy1, -price);
        }
        return sell2;
    }
}
